﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace MailRuWrapper.Server
{
    internal static class  Extensions
    {
        public static String MD5Hash(this string source)
        {
            var _md5Hasher = MD5.Create();

            byte[] _data = _md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(source));

            var _sBuilder = new StringBuilder();

            foreach (var _t in _data)
            {
                _sBuilder.Append(_t.ToString("x2"));
            }
            return _sBuilder.ToString();
        }

        public static int ToInt(this string source)
        {
            return Int32.Parse(source);
        }

        public static Uri ToUri(this string source)
        {
            return new Uri(source);
        }

        public static Boolean ToBoolean(this string source)
        {
            return source == "1";
        }

        public static DateTime ToDateTime(this string source)
        {
            if (String.IsNullOrEmpty(source))
            {
                return DateTime.MinValue;
            }
            int _i;
            if (Int32.TryParse((source), out _i))
            {
                return new DateTime(1970, 1, 1) + new TimeSpan(_i*TimeSpan.TicksPerSecond);
            }
            return DateTime.Parse(source);
        }

        public static string ComputeSIG(this List<string> param, string serverKey)
        {
            if (param == null)
                throw new ArgumentNullException("param");

            var _sBuilder = new StringBuilder();
            param.Sort();
            foreach (var _item in param)
            {
                _sBuilder.Append(_item);
            }

            _sBuilder.Append(serverKey);

            return _sBuilder.ToString().MD5Hash();
        }
    }

}
